package com.zh.common.view

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.zh.common.ktx.color
import com.zh.common.R

class GridItemDecoration(private val space: Int, private val mColor: Int = R.color.transparent) :
    ItemDecoration() {

    private val paint by lazy {
        Paint().apply {
            color = mColor.color()
        }
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view) // item position
        val spanCount = (parent.layoutManager as GridLayoutManager).spanCount // column count
        // 计算间距
        val column = position % spanCount // item column
        outRect.left = space - column * space / spanCount // column * ((1f / spanCount) * space)
        outRect.right =
            (column + 1) * space / spanCount // (spanCount - (column + 1)) * ((1f / spanCount) * space)
        if (position >= spanCount) {
            outRect.top = space // item top
        }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val left = child.left - params.leftMargin
            val right = child.right + params.rightMargin + space
            val top = child.top - params.topMargin
            val bottom = child.bottom + params.bottomMargin + space
            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }
}